/**
 * 维智物联定位SDK工具类
 * 官网：https://lothub.newayz.com/
 */

class WZLocation {
  constructor() {
    this.apiKey = 'hbrFkRczuRbEHlvfThKuX68ZUXNZCWig'; // 通用key
    this.poiApiKey = 'nmf562f2rmWGv0ytmt6vcVWJAWl9Q4HX'; // POI搜索key
    this.baseUrl = 'https://lothub.newayz.com/api';
    this.currentLocation = null;
  }

  /**
   * 获取当前位置
   * @param {Object} options 配置选项
   * @returns {Promise} 位置信息
   */
  getCurrentLocation(options = {}) {
    console.log('[WZ_LOCATION] 开始获取当前位置, options:', options);
    
    return new Promise((resolve, reject) => {
      // 检查定位权限
      uni.getSetting({
        success: (settingRes) => {
          console.log('[WZ_LOCATION] 权限设置:', settingRes.authSetting);
          
          if (settingRes.authSetting['scope.userLocation'] === false) {
            console.warn('[WZ_LOCATION] 用户已拒绝定位权限');
            // 引导用户开启权限
            uni.showModal({
              title: '定位权限',
              content: '需要获取您的位置信息，请在设置中开启定位权限',
              confirmText: '去设置',
              success: (modalRes) => {
                if (modalRes.confirm) {
                  uni.openSetting();
                }
              }
            });
          }
          
          // 尝试获取位置
          console.log('[WZ_LOCATION] 调用uni.getLocation');
          uni.getLocation({
            type: 'gcj02', // 使用国测局坐标系
            geocode: true,
            altitude: true,
            success: (res) => {
              console.log('[WZ_LOCATION] 获取位置成功:', {
                latitude: res.latitude,
                longitude: res.longitude,
                accuracy: res.accuracy,
                altitude: res.altitude,
                verticalAccuracy: res.verticalAccuracy,
                horizontalAccuracy: res.horizontalAccuracy,
                speed: res.speed,
                address: res.address
              });
              
              this.currentLocation = {
                latitude: res.latitude,
                longitude: res.longitude,
                address: res.address || '',
                city: res.address ? this.extractCity(res.address) : '',
                accuracy: res.accuracy || 0
              };
              
              console.log('[WZ_LOCATION] 处理后的位置信息:', this.currentLocation);
              resolve(this.currentLocation);
            },
            fail: (err) => {
              console.error('[WZ_LOCATION] 获取位置失败:', {
                errMsg: err.errMsg,
                errCode: err.errCode || 'unknown',
                error: err
              });
              
              // 根据错误类型给出不同提示
              let errorMsg = '获取位置失败';
              if (err.errMsg) {
                if (err.errMsg.includes('auth deny')) {
                  errorMsg = '定位权限被拒绝，请在设置中开启定位权限';
                } else if (err.errMsg.includes('timeout')) {
                  errorMsg = '定位超时，请检查网络连接';
                } else if (err.errMsg.includes('system deny')) {
                  errorMsg = '系统拒绝定位，请检查设备定位服务是否开启';
                }
              }
              
              console.warn('[WZ_LOCATION] 使用默认位置（北京）');
              // 如果获取位置失败，使用默认位置（北京）
              this.currentLocation = {
                latitude: 39.9042,
                longitude: 116.4074,
                address: '北京市朝阳区',
                city: '北京市',
                accuracy: 0,
                isDefault: true,
                errorMsg: errorMsg
              };
              
              console.log('[WZ_LOCATION] 默认位置信息:', this.currentLocation);
              resolve(this.currentLocation);
            }
          });
        },
        fail: (err) => {
          console.error('[WZ_LOCATION] 获取权限设置失败:', err);
          // 继续尝试获取位置
          uni.getLocation({
            type: 'gcj02',
            geocode: true,
            success: (res) => {
              console.log('[WZ_LOCATION] 获取位置成功（无权限检查）:', res);
              this.currentLocation = {
                latitude: res.latitude,
                longitude: res.longitude,
                address: res.address || '',
                city: res.address ? this.extractCity(res.address) : ''
              };
              resolve(this.currentLocation);
            },
            fail: (err) => {
              console.error('[WZ_LOCATION] 获取位置失败（无权限检查）:', err);
              this.currentLocation = {
                latitude: 39.9042,
                longitude: 116.4074,
                address: '北京市朝阳区',
                city: '北京市',
                isDefault: true
              };
              resolve(this.currentLocation);
            }
          });
        }
      });
    });
  }

  /**
   * 逆地理编码 - 根据坐标获取地址信息
   * @param {Number} latitude 纬度
   * @param {Number} longitude 经度
   * @returns {Promise} 地址信息
   */
  async reverseGeocode(latitude, longitude) {
    console.log('[WZ_LOCATION] 开始逆地理编码:', { latitude, longitude });
    
    try {
      const requestData = {
        key: this.apiKey,
        lat: latitude,
        lng: longitude,
        format: 'json'
      };
      
      console.log('[WZ_LOCATION] 逆地理编码请求参数:', requestData);
      console.log('[WZ_LOCATION] 请求URL:', `${this.baseUrl}/geocode/reverse`);
      
      const response = await uni.request({
        url: `${this.baseUrl}/geocode/reverse`,
        method: 'GET',
        data: requestData,
        timeout: 10000
      });
      
      console.log('[WZ_LOCATION] 逆地理编码响应:', {
        statusCode: response.statusCode,
        data: response.data
      });
      
      if (response.statusCode !== 200) {
        throw new Error(`HTTP请求失败: ${response.statusCode}`);
      }
      
      if (response.data && response.data.status === 'OK') {
        const result = {
          address: response.data.result.formatted_address,
          city: response.data.result.addressComponent.city,
          district: response.data.result.addressComponent.district,
          province: response.data.result.addressComponent.province
        };
        
        console.log('[WZ_LOCATION] 逆地理编码成功:', result);
        return result;
      } else {
        console.warn('[WZ_LOCATION] 逆地理编码API返回错误:', response.data);
        throw new Error(`API错误: ${response.data?.message || '逆地理编码失败'}`);
      }
    } catch (error) {
      console.error('[WZ_LOCATION] 逆地理编码错误:', {
        message: error.message,
        stack: error.stack,
        error: error
      });
      
      // 返回默认地址信息
      const defaultResult = {
        address: '位置获取失败',
        city: '未知',
        district: '',
        province: '',
        error: error.message
      };
      
      console.log('[WZ_LOCATION] 返回默认地址信息:', defaultResult);
      return defaultResult;
    }
  }

  /**
   * 地理编码 - 根据地址获取坐标
   * @param {String} address 地址
   * @returns {Promise} 坐标信息
   */
  async geocode(address) {
    try {
      const response = await uni.request({
        url: `${this.baseUrl}/geocode`,
        method: 'GET',
        data: {
          key: this.apiKey,
          address: address,
          format: 'json'
        }
      });
      
      if (response.data && response.data.status === 'OK') {
        const location = response.data.result.location;
        return {
          latitude: location.lat,
          longitude: location.lng
        };
      }
      throw new Error('地理编码失败');
    } catch (error) {
      console.error('地理编码错误:', error);
      return null;
    }
  }

  /**
   * POI搜索
   * @param {String} keyword 搜索关键词
   * @param {Object} location 中心点坐标 {latitude, longitude}
   * @param {Number} radius 搜索半径（米）
   * @returns {Promise} POI列表
   */
  async searchPOI(keyword, location = null, radius = 5000) {
    console.log('[WZ_LOCATION] 开始POI搜索:', { keyword, location, radius });
    
    try {
      const searchLocation = location || this.currentLocation;
      console.log('[WZ_LOCATION] 使用的搜索位置:', searchLocation);
      
      if (!searchLocation) {
        console.error('[WZ_LOCATION] 位置信息不可用');
        throw new Error('位置信息不可用');
      }

      const requestData = {
        key: this.poiApiKey,
        query: keyword,
        lat: searchLocation.latitude,
        lng: searchLocation.longitude,
        radius: radius,
        format: 'json'
      };
      
      console.log('[WZ_LOCATION] POI搜索请求参数:', requestData);
      console.log('[WZ_LOCATION] 请求URL:', `${this.baseUrl}/poi/search`);

      const response = await uni.request({
        url: `${this.baseUrl}/poi/search`,
        method: 'GET',
        data: requestData,
        timeout: 15000
      });
      
      console.log('[WZ_LOCATION] POI搜索响应:', {
        statusCode: response.statusCode,
        data: response.data
      });
      
      if (response.statusCode !== 200) {
        throw new Error(`HTTP请求失败: ${response.statusCode}`);
      }
      
      if (response.data && response.data.status === 'OK') {
        const results = response.data.results.map(poi => {
          const poiLocation = { latitude: poi.location.lat, longitude: poi.location.lng };
          const distance = this.calculateDistance(searchLocation, poiLocation);
          
          return {
            id: poi.id,
            name: poi.name,
            address: poi.address,
            latitude: poi.location.lat,
            longitude: poi.location.lng,
            distance: distance,
            category: poi.category
          };
        });
        
        console.log('[WZ_LOCATION] POI搜索成功，找到', results.length, '个结果');
        console.log('[WZ_LOCATION] POI搜索结果:', results);
        return results;
      } else {
        console.warn('[WZ_LOCATION] POI搜索API返回错误:', response.data);
        throw new Error(`API错误: ${response.data?.message || 'POI搜索失败'}`);
      }
    } catch (error) {
      console.error('[WZ_LOCATION] POI搜索错误:', {
        message: error.message,
        stack: error.stack,
        error: error
      });
      
      console.log('[WZ_LOCATION] 返回空的POI列表');
      return [];
    }
  }

  /**
   * 计算两点间距离
   * @param {Object} point1 起点 {latitude, longitude}
   * @param {Object} point2 终点 {latitude, longitude}
   * @returns {Number} 距离（米）
   */
  calculateDistance(point1, point2) {
    const R = 6371000; // 地球半径（米）
    const lat1Rad = point1.latitude * Math.PI / 180;
    const lat2Rad = point2.latitude * Math.PI / 180;
    const deltaLatRad = (point2.latitude - point1.latitude) * Math.PI / 180;
    const deltaLngRad = (point2.longitude - point1.longitude) * Math.PI / 180;

    const a = Math.sin(deltaLatRad / 2) * Math.sin(deltaLatRad / 2) +
              Math.cos(lat1Rad) * Math.cos(lat2Rad) *
              Math.sin(deltaLngRad / 2) * Math.sin(deltaLngRad / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

    return R * c;
  }

  /**
   * 格式化距离显示
   * @param {Number} distance 距离（米）
   * @returns {String} 格式化后的距离
   */
  formatDistance(distance) {
    if (distance < 1000) {
      return `${Math.round(distance)}m`;
    } else {
      return `${(distance / 1000).toFixed(1)}km`;
    }
  }

  /**
   * 从地址中提取城市名称
   * @param {String} address 完整地址
   * @returns {String} 城市名称
   */
  extractCity(address) {
    const cityMatch = address.match(/(\S+市)/); 
    return cityMatch ? cityMatch[1] : '未知城市';
  }

  /**
   * 选择位置（打开地图选择器）
   * @returns {Promise} 选择的位置信息
   */
  chooseLocation() {
    console.log('[WZ_LOCATION] 开始选择位置');
    
    return new Promise((resolve, reject) => {
      // 检查定位权限
      uni.getSetting({
        success: (settingRes) => {
          console.log('[WZ_LOCATION] 选择位置权限检查:', settingRes.authSetting);
          
          if (settingRes.authSetting['scope.userLocation'] === false) {
            console.warn('[WZ_LOCATION] 选择位置需要定位权限');
            uni.showModal({
              title: '定位权限',
              content: '选择位置需要定位权限，请在设置中开启',
              confirmText: '去设置',
              success: (modalRes) => {
                if (modalRes.confirm) {
                  uni.openSetting({
                    success: () => {
                      console.log('[WZ_LOCATION] 用户已打开设置页面');
                    }
                  });
                }
              }
            });
            reject(new Error('定位权限被拒绝'));
            return;
          }
          
          console.log('[WZ_LOCATION] 调用uni.chooseLocation');
          uni.chooseLocation({
            success: async (res) => {
              console.log('[WZ_LOCATION] 选择位置成功:', {
                latitude: res.latitude,
                longitude: res.longitude,
                address: res.address,
                name: res.name
              });
              
              const locationInfo = {
                latitude: res.latitude,
                longitude: res.longitude,
                address: res.address,
                name: res.name,
                city: this.extractCity(res.address)
              };
              
              console.log('[WZ_LOCATION] 处理后的选择位置信息:', locationInfo);
              this.currentLocation = locationInfo;
              resolve(locationInfo);
            },
            fail: (err) => {
              console.error('[WZ_LOCATION] 选择位置失败:', {
                errMsg: err.errMsg,
                errCode: err.errCode || 'unknown',
                error: err
              });
              
              // 根据错误类型给出不同提示
              let errorMsg = '选择位置失败';
              if (err.errMsg) {
                if (err.errMsg.includes('cancel')) {
                  errorMsg = '用户取消选择位置';
                } else if (err.errMsg.includes('auth deny')) {
                  errorMsg = '定位权限被拒绝';
                } else if (err.errMsg.includes('system deny')) {
                  errorMsg = '系统拒绝访问位置服务';
                }
              }
              
              console.warn('[WZ_LOCATION] 选择位置错误信息:', errorMsg);
              reject(new Error(errorMsg));
            }
          });
        },
        fail: (err) => {
          console.error('[WZ_LOCATION] 获取权限设置失败:', err);
          // 继续尝试选择位置
          uni.chooseLocation({
            success: async (res) => {
              console.log('[WZ_LOCATION] 选择位置成功（无权限检查）:', res);
              const locationInfo = {
                latitude: res.latitude,
                longitude: res.longitude,
                address: res.address,
                name: res.name,
                city: this.extractCity(res.address)
              };
              this.currentLocation = locationInfo;
              resolve(locationInfo);
            },
            fail: (err) => {
              console.error('[WZ_LOCATION] 选择位置失败（无权限检查）:', err);
              reject(err);
            }
          });
        }
      });
    });
  }
}

// 创建单例实例
const wzLocation = new WZLocation();

export default wzLocation;